package com.getpebble.android.connection;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.framework.fragment.PblListFragment;
import com.getpebble.android.common.model.ConnectionGoal;
import com.getpebble.android.common.model.ConnectionStatus;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.FrameworkState.EventType;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.framework.FrameworkEventReceiver;
import com.getpebble.android.framework.FrameworkEventReceiver.IFrameworkEventListener;
import com.getpebble.android.onboarding.activity.OnboardingActivity;
import com.getpebble.android.util.BluetoothUtil;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;

public class ConnectionManagerFragment extends PblListFragment implements LoaderCallbacks<Cursor>, OnClickListener, OnItemClickListener, IFrameworkEventListener {
    private static final String TAG = ConnectionManagerFragment.class.getSimpleName();
    private static final Handler sHandler = new Handler(Looper.getMainLooper());
    private final String SORT_ORDER = "connection_status DESC, last_connected_time DESC, rssi DESC, friendly_name ASC";
    private CursorAdapter mCursorAdapter = null;
    private CursorLoader mCursorLoader = null;
    private Button mDiscoverButton = null;
    private ProgressBar mDiscoveryProgressBar = null;
    private TextView mHeaderTextView = null;
    private boolean mIsDialogVisible = false;
    private boolean mIsDiscovering = false;
    private LinearLayout mOnboardingBanner = null;
    private boolean mShowedPebbleTimeDialog = false;

    static /* synthetic */ class AnonymousClass9 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$common$model$ConnectionStatus = new int[ConnectionStatus.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType = new int[EventType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$common$model$ConnectionStatus[ConnectionStatus.CONNECTED.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$ConnectionStatus[ConnectionStatus.CONNECTING.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$ConnectionStatus[ConnectionStatus.DISCONNECTED.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$ConnectionStatus[ConnectionStatus.UNKNOWN.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[EventType.DISCOVERY_STATE_CHANGED.ordinal()] = 1;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[EventType.BLUETOOTH_STATE_CHANGED.ordinal()] = 2;
            } catch (NoSuchFieldError e6) {
            }
        }
    }

    private void initialize() {
        LoaderManager loaderManager = getLoaderManager();
        if (loaderManager != null) {
            loaderManager.initLoader(42, new Bundle(), this);
        }
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.init(inflater, container, savedInstanceState);
        this.mDiscoveryProgressBar = (ProgressBar) container.findViewById(R.id.discovery_progress_bar);
        this.mOnboardingBanner = (LinearLayout) container.findViewById(R.id.onboarding_banner_layout);
        this.mDiscoveryProgressBar.setVisibility(8);
        this.mDiscoverButton = (Button) container.findViewById(R.id.btn_discover);
        this.mDiscoverButton.setOnClickListener(this);
        this.mHeaderTextView = (TextView) container.findViewById(R.id.connect_to_another_pebble);
        TextView onboardingBannerTextView = (TextView) container.findViewById(R.id.onboarding_banner);
        if (!isOnboarding()) {
            onboardingBannerTextView.setVisibility(8);
        }
        setOnItemClickListener(this);
        setDivider(new ColorDrawable(getResources().getColor(R.color.connection_manager_bg)));
        setDividerHeight(1);
        setBackgroundColor(getResources().getColor(R.color.connection_manager_bg));
        setFastScrollEnabled();
        if (isOnboarding()) {
            showEnableBluetoothDialog();
        }
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        initialize();
    }

    public void onResume() {
        super.onResume();
        FrameworkEventReceiver.registerFrameworkStateEventListener(this);
        Trace.verbose(TAG, "onResume() isOnboarding = " + isOnboarding());
        updateUI();
        if (!isConnected()) {
            if ((this.mCursorAdapter != null) && this.mCursorAdapter.isEmpty() && !this.mIsDiscovering) {
                Trace.debug(TAG, "Done loading adapter, no devices, and not discovering; starting discovery");
                toggleDiscovery();
            }
            showPebbleTimeDialogIfRequired(FrameworkEventReceiver.getLatestFrameworkState());
        } else if (isOnboarding()) {
            skipToNextOnboardingFragment();
        }
    }

    private void showPebbleTimeDialogIfRequired(FrameworkState newState) {
        if (newState != null && !this.mShowedPebbleTimeDialog && newState.getPebbleTimeConnected()) {
            Activity activity = getActivity();
            if (activity == null) {
                Trace.warning(TAG, "showPebbleTimeDialogIfRequired() activity is null");
                return;
            }
            this.mShowedPebbleTimeDialog = true;
            new Builder(activity).setTitle(R.string.connection_pebble_time_title).setMessage(R.string.connection_pebble_time_body).setPositiveButton(getString(R.string.connection_pebble_time_positive_button), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    ConnectionManagerFragment.goToPlayStoreForPebbleTimeApp(PebbleApplication.getAppContext());
                }
            }).setNegativeButton(getResources().getString(R.string.connection_pebble_time_negative_button), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                }
            }).setCancelable(false).show();
        }
    }

    public static void goToPlayStoreForPebbleTimeApp(Context context) {
        Intent timeInstallIntent = new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=com.getpebble.android.basalt"));
        timeInstallIntent.setFlags(268435456);
        try {
            context.startActivity(timeInstallIntent);
        } catch (ActivityNotFoundException e) {
            Trace.debug(TAG, "Error loading play store for Pebble Time; showing web store", e);
            context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=com.getpebble.android.basalt")));
        }
    }

    private void showEnableBluetoothDialog() {
        if (PebbleApplication.getConnectedDevice() == null && !BluetoothUtil.isBluetoothEnabled()) {
            startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
        }
    }

    public void onPause() {
        FrameworkEventReceiver.unregisterFrameworkStateEventListener(this);
        this.mIsDiscovering = false;
        PebbleApplication.getFrameworkInterface().stopDiscovery();
        updateUI();
        super.onPause();
    }

    public int getLayoutId() {
        return R.layout.fragment_connection_manager;
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        switch (id) {
            case 42:
                this.mCursorLoader = new CursorLoader(getActivity(), PblDeviceModel.TABLE_URI, PblDeviceModel.ALL_FIELDS_PROJECTION, null, null, "connection_status DESC, last_connected_time DESC, rssi DESC, friendly_name ASC");
                break;
        }
        return this.mCursorLoader;
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.debug(TAG, "Activity is null, ignoring onLoadFinished");
            return;
        }
        if (this.mCursorAdapter == null) {
            this.mCursorAdapter = new PblDeviceAdapter(activity, data);
            setAdapter(this.mCursorAdapter);
            if (this.mCursorAdapter.isEmpty() && !this.mIsDiscovering) {
                Trace.debug(TAG, "Empty adapter and not discovering; starting discovery");
                toggleDiscovery();
            }
        } else {
            this.mCursorAdapter.changeCursor(data);
        }
        if (this.mCursorAdapter.isEmpty()) {
            showEmptyView();
        } else {
            showFullView();
        }
        updateUI();
        if (isOnboarding() && isConnected()) {
            skipToNextOnboardingFragment();
        }
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        if (loader == this.mCursorLoader) {
            Cursor c = this.mCursorAdapter.getCursor();
            if (c != null) {
                c.close();
            }
            this.mCursorAdapter = null;
        }
        updateUI();
    }

    public void onClick(View v) {
        if (v != this.mDiscoverButton) {
            return;
        }
        if (BluetoothUtil.isBluetoothEnabled()) {
            toggleDiscovery();
            showFullView();
            return;
        }
        startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
    }

    private void updateUI() {
        if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
            Trace.error(TAG, "Cannot update UI!");
            return;
        }
        if (this.mDiscoverButton != null) {
            if (this.mIsDiscovering) {
                if (this.mDiscoveryProgressBar != null) {
                    if (!isOnboarding()) {
                        this.mOnboardingBanner.setVisibility(0);
                    }
                    this.mDiscoveryProgressBar.setVisibility(0);
                }
                this.mDiscoverButton.setText(getString(R.string.connection_manager_stop_searching));
            } else {
                if (this.mDiscoveryProgressBar != null) {
                    if (!isOnboarding()) {
                        this.mOnboardingBanner.setVisibility(8);
                    }
                    this.mDiscoveryProgressBar.setVisibility(8);
                }
                this.mDiscoverButton.setText(getString(R.string.connection_manager_find_a_new_pebble));
            }
        }
        setHeaderText();
    }

    private void toggleDiscovery() {
        if (this.mIsDiscovering) {
            PebbleApplication.getFrameworkInterface().stopDiscovery();
        } else {
            PebbleApplication.getFrameworkInterface().startDiscovery();
        }
    }

    public void onFrameworkStateChanged(FrameworkState newState) {
        if (newState != null) {
            showPebbleTimeDialogIfRequired(newState);
            EventType eventType = newState.getLastEvent();
            if (eventType != null) {
                switch (AnonymousClass9.$SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[eventType.ordinal()]) {
                    case SMTPMessage.RETURN_FULL /*1*/:
                        this.mIsDiscovering = newState.isDiscoveryInProgress();
                        sHandler.post(new Runnable() {
                            public void run() {
                                ConnectionManagerFragment.this.updateUI();
                            }
                        });
                        return;
                    case SMTPMessage.RETURN_HDRS /*2*/:
                        if (!newState.isBluetoothEnabled()) {
                            requestBTEnable();
                            return;
                        }
                        return;
                    default:
                        return;
                }
            }
        }
    }

    private void requestBTEnable() {
        startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        if (this.mCursorAdapter == null) {
            Trace.warning(TAG, "Null cursor adapter; dropping click");
        } else if (BluetoothUtil.isBluetoothEnabled()) {
            Cursor cursor = (Cursor) this.mCursorAdapter.getItem(position);
            if (cursor == null) {
                Trace.warning(TAG, "Null cursor at position " + position + "; dropping click");
                return;
            }
            PblDeviceRecord device = PblDeviceModel.getPblDeviceRecordFromCursor(cursor);
            switch (AnonymousClass9.$SwitchMap$com$getpebble$android$common$model$ConnectionStatus[device.connectionStatus.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    Trace.debug(TAG, "Device is connected; disconnect");
                    disconnectWithCheck(device.pblDevice, device.connectionStatus);
                    return;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    if (!device.connectionGoal.equals(ConnectionGoal.DISCONNECT)) {
                        Trace.debug(TAG, "Device is connecting; cancel by disconnecting");
                        disconnectWithCheck(device.pblDevice, device.connectionStatus);
                        return;
                    }
                    return;
                case ListInfo.INDETERMINATE /*3*/:
                    Trace.debug(TAG, "Device is disconnected; connecting");
                    connectWithCheck(device.pblDevice, device.connectionStatus);
                    break;
            }
            Trace.info(TAG, "Unknown connection status; requesting connection");
            connectWithCheck(device.pblDevice, device.connectionStatus);
        } else {
            startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
        }
    }

    private void connectWithCheck(PblDevice device, ConnectionStatus status) {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "Activity is null, dropping connection request");
            return;
        }
        boolean isUserInformedConnectingMeansDisconnecting = new PblPreferences(activity).getBooleanData(PrefKey.NAGGED_ABOUT_CONNECT_IS_DISCONNECT, false);
        boolean isPebbleConnected;
        if (PebbleApplication.getConnectedDevice() != null) {
            isPebbleConnected = true;
        } else {
            isPebbleConnected = false;
        }
        if (isUserInformedConnectingMeansDisconnecting || !isPebbleConnected) {
            this.mShowedPebbleTimeDialog = false;
            PebbleApplication.getFrameworkInterface().connectToDevice(device);
        } else if (!this.mIsDialogVisible) {
            showConnectIsDisconnectConfirmationDialog(device, status);
        }
    }

    private void showConnectIsDisconnectConfirmationDialog(final PblDevice device, ConnectionStatus status) {
        int strTitle;
        int strBody;
        this.mIsDialogVisible = true;
        Trace.debug(TAG, "showConnectIsDisconnectConfirmationDialog");
        if (status == ConnectionStatus.CONNECTING) {
            strTitle = R.string.connection_manager_dialog_nag_connect_will_cancel_title;
            strBody = R.string.connection_manager_dialog_nag_connect_will_cancel_text;
        } else {
            strTitle = R.string.connection_manager_dialog_nag_connect_will_disconnect_title;
            strBody = R.string.connection_manager_dialog_nag_connect_will_disconnect_text;
        }
        Activity activity = getActivity();
        if (activity != null) {
            final PblPreferences preferences = new PblPreferences(activity.getApplicationContext());
            new Builder(activity).setTitle(strTitle).setMessage(strBody).setPositiveButton(getString(R.string.connection_manager_dialog_text_connect), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    preferences.setBooleanData(PrefKey.NAGGED_ABOUT_CONNECT_IS_DISCONNECT, true);
                    PebbleApplication.getFrameworkInterface().connectToDevice(device);
                    ConnectionManagerFragment.this.mIsDialogVisible = false;
                }
            }).setNegativeButton(getResources().getString(R.string.connection_manager_dialog_text_back), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    ConnectionManagerFragment.this.mIsDialogVisible = false;
                }
            }).setCancelable(false).show();
        }
    }

    private void disconnectWithCheck(PblDevice device, ConnectionStatus status) {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "Received request to disconnect but activity is null; dropping");
        } else if (new PblPreferences(activity).getBooleanData(PrefKey.NAGGED_ABOUT_DISCONNECT, false)) {
            PebbleApplication.getFrameworkInterface().disconnectFromDevice(device);
        } else if (!this.mIsDialogVisible) {
            showDisconnectConfirmationDialog(device, status);
        }
    }

    private void showDisconnectConfirmationDialog(final PblDevice device, ConnectionStatus status) {
        int strTitle;
        int strBody;
        this.mIsDialogVisible = true;
        Trace.debug(TAG, "showDisconnectConfirmationDialog");
        if (status == ConnectionStatus.CONNECTING) {
            strTitle = R.string.connection_manager_dialog_nag_cancel_connect_title;
            strBody = R.string.connection_manager_dialog_nag_cancel_connect_text;
        } else {
            strTitle = R.string.connection_manager_dialog_nag_disconnect_title;
            strBody = R.string.connection_manager_dialog_nag_disconnect_text;
        }
        Activity activity = getActivity();
        if (activity != null) {
            final PblPreferences preferences = new PblPreferences(activity.getApplicationContext());
            new Builder(activity).setTitle(strTitle).setMessage(strBody).setPositiveButton(getString(R.string.connection_manager_dialog_text_disconnect), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    preferences.setBooleanData(PrefKey.NAGGED_ABOUT_DISCONNECT, true);
                    PebbleApplication.getFrameworkInterface().disconnectFromDevice(device);
                    ConnectionManagerFragment.this.mIsDialogVisible = false;
                }
            }).setNegativeButton(getResources().getString(R.string.disconnect_confirmation_dialog_negative_button), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    ConnectionManagerFragment.this.mIsDialogVisible = false;
                }
            }).setCancelable(false).show();
        }
    }

    private void setHeaderText() {
        if (this.mHeaderTextView == null) {
            Trace.debug(TAG, "Header text view is null");
        } else if (getActivity() == null) {
            Trace.warning(TAG, "activity is null");
        } else if (this.mCursorAdapter == null) {
        } else {
            if (this.mCursorAdapter.isEmpty()) {
                if (this.mIsDiscovering) {
                    this.mHeaderTextView.setText(R.string.connection_manager_searching_for_nearby_pebbles);
                } else {
                    this.mHeaderTextView.setText(R.string.connection_manager_no_pebbles_found);
                }
            } else if (isConnected()) {
                this.mHeaderTextView.setText(R.string.connection_manager_connect_different);
            } else {
                this.mHeaderTextView.setText(R.string.connection_manager_connect_new);
            }
        }
    }

    private boolean isOnboarding() {
        return getActivity() instanceof OnboardingActivity;
    }

    private static boolean isConnected() {
        return PebbleApplication.getConnectedDevice() != null;
    }

    private boolean skipToNextOnboardingFragment() {
        return sHandler.post(new Runnable() {
            public void run() {
                Activity activity = ConnectionManagerFragment.this.getActivity();
                if (activity instanceof OnboardingActivity) {
                    ((OnboardingActivity) activity).showCurrentScreen();
                }
            }
        });
    }
}
